package com.yexx.starter.security.pwd;

import com.yexx.starter.security.basic.BasicLoginFilter;
import com.yexx.starter.security.basic.constant.SecurityConstants;
import com.yexx.utils.CacheUtil;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Description: 账户密码登录filter
 *
 * @author: zuomin (myleszelic@outlook.com)
 * @date: 2020/11/02 16:32
 */
public class PwdAuthenticationFilter extends BasicLoginFilter {

    private CacheUtil cacheUtil;

    public PwdAuthenticationFilter(String defaultFilterProcessesUrl, String failureUrl, Boolean singleSignOn) {
        super(defaultFilterProcessesUrl, failureUrl, singleSignOn);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        String deviceUuid = obtainDeviceUuid(request);
        String phoneNum = obtainMobile(request);
        String pwd = obtainPassword(request);
        if (StringUtils.isEmpty(phoneNum) || StringUtils.isEmpty(pwd)) {
            // 捕获到的异常会交给 {@link BasicLoginFilter#unsuccessfulAuthentication(...) }
            throw new InternalAuthenticationServiceException("用户名或者密码错误");
        }
        phoneNum = phoneNum.trim();
        pwd = pwd.trim();
        //创建SmsCodeAuthenticationToken(未认证)
        PwdAuthenticationToken authRequest = new PwdAuthenticationToken(phoneNum, pwd, deviceUuid);
        //设置用户信息
        setDetails(request, authRequest);
        return this.getAuthenticationManager().authenticate(authRequest);
    }

    protected String obtainPassword(HttpServletRequest request) {
        return request.getParameter(SecurityConstants.PARAMETER.LOGIN_PWD);
    }

    @Override
    public CacheUtil getCacheUtil() {
        return cacheUtil;
    }

    public void setCacheUtil(CacheUtil cacheUtil) {
        this.cacheUtil = cacheUtil;
    }

}
